package com.wydpp.utils;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wydpp.properties.ZlmProperties;
import com.wydpp.constant.ZlmConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class ZlmUtils {

    private static final Logger log = LoggerFactory.getLogger(ZlmUtils.class);

    public static Map openRtpServer(String streamId) {
        ZlmProperties bean = SpringUtil.getBean(ZlmProperties.class);
        String url = bean.getIp() + ":" + bean.getPort() + ZlmConstant.openRtpServer + "?secret=" + bean.getSecret() + "&port=0&tcp_mode=0&stream_id=" + streamId + "";
        String str = HttpUtil.get(url);
        JSONObject entries = JSONUtil.parseObj(str);
        Integer i = Integer.valueOf(entries.get("port").toString());
        Map<String, Object> map = new HashMap<>();
        map.put("ip", bean.getIp());
        map.put("port", i);
        return map;
    }


    public static boolean closeRtpServer(String streamId) {
        ZlmProperties bean = SpringUtil.getBean(ZlmProperties.class);
        String url = bean.getIp() + ":" + bean.getPort() + ZlmConstant.closeRtpServer + "?secret=" + bean.getSecret() + "&stream_id=" + streamId + "";
        String str = HttpUtil.get(url);
        log.info(str);
        JSONObject entries = JSONUtil.parseObj(str);

        Integer i = Integer.valueOf(entries.get("hit").toString());
        if (i == 1) {
            return true;
        }
        return true;
    }

    public static int startSendRtp(String streamId, String ip, int port) {
        ZlmProperties bean = SpringUtil.getBean(ZlmProperties.class);
        String url = bean.getIp() + ":" + bean.getPort() + ZlmConstant.startSendRtp + "?secret=" + bean.getSecret() + "&vhost=__defaultVhost__&app=rtp&stream=" + streamId + "&ssrc=1&dst_url=" + ip + "&dst_port=" + port + "&is_udp=1";
        String str = HttpUtil.get(url);
        log.info(str);
        JSONObject entries = JSONUtil.parseObj(str);
        Integer i = Integer.valueOf(entries.get("local_port").toString());
        return i;
    }
}
